-module(handler_usr_login).

-export([init/3]).
%% -export([handle/2]).
-export([info/3]).
-export([terminate/3,test/0]).

-include("common.hrl").

%%init/2 回调函数也可以用来告诉cowboy，这是一个不同类型的handler，Cowboy应该做一些其他处理。为了方便使用，
%% 如果返回handler类型的模块名称，就可以切换handler处理模块。

%%Cowboy提供了三种可选handler类型：cowboy_reset, Cowboy_websocke和cowboy_loop。另外也可以自己定义handler类型。

init(_, Req, _Opts) ->
	?log_trace("global_wx_login_handler,peer=~p,path=~p,body=~p",[cowboy_req:get(peer,Req),cowboy_req:get(path,Req),cowboy_req:get(buffer,Req)]),
	{Method, Req2} = cowboy_req:method(Req),
	HasBody = cowboy_req:has_body(Req2),
%% 	?log("Req,..............-=~p",[Req]),
	case get_input_data(Method, HasBody,Req2) of
		{ok, {Code,Channel_ID}, Req3} ->
			?log("_Code.....................=~p",[Code]),
			server_tools:send_to_agent_mng({login_check,self(),util:to_list(Code),util:to_binary(Channel_ID)}),
			{loop, Req3, undefined, 10000, hibernate};
		_ ->?log_warning("sssssssssssssHasBody =~p",[HasBody]),
			{ok, NewReq2} = cowboy_req:reply(404,Req2),
			{shutdown, NewReq2, undefined}
	end.

%%最后我们返回一个三元组。ok 表示handler允许成功，然后返回处理过后的 Req 给Cowboy。 三元组的最后一个元素是一个贯穿在handler所有回调一个state。常规的HTTP handlers一般只附加一个回调函数，
%% 	{ok, Req, undefined}.
%%192.168.0.35:8001/usr_login?code=123
%% handle/2,是特定于简单HTTP处理器的。你将要在此处理请求的


headers() ->
	#{
	  <<"content-type">> => <<"text/plain">>,
	  <<"Access-Control-Allow-Origin">> => <<"*">>,
	  <<"Access-Control-Allow-Credentials">> => <<"true">>,
	  <<"Access-Control-Allow-Headers">> => <<"Origin,Content-Type,Accept,token,X-Requested-With">>}.

info({reply, Body}, Req, State) ->
	{ok, Req2} = cowboy_req:reply(200 ,[{<<"content-type">>,<<"text/plain">>},
										{<<"Access-Control-Allow-Origin">>,<<"*">>}
										],
								  Body, Req),
	?log("reply.........global_wx_login_handler........Body=~p",[Body]),
	{ok, Req2, State};
info({http, Msg},Req, State) ->
	?log("Msg............................................=~p",[Msg]),
	fun_http:async_http_response(Msg),
	{ok, Req,State};
info(_Msg, Req, State) ->
	?debug("unknown msg,~p",[_Msg]),
    {loop, Req, State, hibernate}.

%%当调用了 cowboy:req/4, Cowboy会马上返回一个客户端响应
%%通过一个cowboy_http_req:body_qs(Req)函数，就可以把body 里面通过POST传过来的值了，在通过匹配拿出想要的信息

test() ->headers().

get_input_data(<<"GET">>, false,Req) ->
	
	case cowboy_req:qs_val(<<"code">>, Req) of
		{Code, Req2} when erlang:is_binary(Code)  ->
			{ok, util:to_integer(Code), Req2};
		_ -> Req
	end;
%% 	[{<<"{\"code\":\"0231mteo0AS6cl1YsWdo0hcceo01mter\",\"channel_id\":\"test\"}">>,
%%                                                         true}]		
get_input_data(<<"POST">>, true, Req2) ->
%% 	Data = cowboy_req:get(buffer,Req2),
	case cowboy_req:body_qs(Req2) of
		{ok, PostVals, Req3} ->
			?log("PostVals.........login.....=~p",[PostVals]),
			case PostVals of
				[{Data, _}] ->
					case rfc4627:decode(Data) of
						{ok, {obj, KvList}, _Reminder} ->
							if length(KvList) >1 ->
								   case util:get_values(["code","channel_id"], KvList) of
									   [Code,Channel_ID] -> {ok, {Code,Channel_ID}, Req3};
									   _ ->?log_warning("eeeeeeeeeeeee"), Req3
								   end;
							   true ->
								   case util:get_values(["code"], KvList) of
									   [Code] -> {ok, {Code,""}, Req3};
									   _ ->Req3
								   end
							end;
						_ -> Req3
					end;	
				_ ->?log_warning("mmmmmmmmmmmm"), Req3
			end;
		_ -> Req2
	end;
get_input_data(_Method, _HasBody, Req) ->?log_warning("22222222 _Method =~p",[_Method]), Req.

%%这个回调函数是为了cleanup保留下来的。该函数不能发送响应给客户端。也没有其他返回值（只能返回ok）
%%terminate/3之所以是可选是因为其极少会用到。Cleanup应该在各自的进程中直接处理。（通过监控handler进程来知道其何时退出）

terminate(_Reason, _Req, _State) ->
	ok.

%% headers =>
%%               #{<<"accept">> => <<"*/*">>,<<"content-length">> => <<"23">>,
%%                 <<"content-type">> => <<"application/x-www-form-urlencoded">>,
%%                 <<"host">> => <<"localhost:9888">>,
%%                 <<"user-agent">> => <<"curl/7.54.0">>},